package com.hengxinguotong.zhihuichengjian.ui.tower.violation;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.TowerViolationListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.TowerViolation;
import com.hengxinguotong.zhihuichengjian.bean.TowerViolationCount;
import com.hengxinguotong.zhihuichengjian.bean.TowerViolationCountRes;
import com.hengxinguotong.zhihuichengjian.customtimepicker.TimePickerActivity;
import com.hengxinguotong.zhihuichengjian.customtimepicker.bean.DayTimeEntity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.safetystudy.CalendarListActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/2/24
 *
 * 塔吊违章
 */

public class TowerViolationListActivity extends BaseActivity implements View.OnClickListener, TowerViolationListAdapter.OnClickListener {
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.search_date_tv)
    HXTextView searchDateTv;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;
    @BindView(R.id.violation_count_tv)
    HXTextView violationCountTv;
    @BindView(R.id.empty_img)
    ImageView emptyImg;

    private PullableRecyclerView dataRv;

    private List<TowerViolation> towerViolationList;
    private TowerViolationListAdapter towerViolationAdapter;
    private String startTime, endTime;
    private int pageIndex = 1;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case Constants.UPDATE:
                    TowerViolationCount towerViolationCount = (TowerViolationCount) msg.obj;
                    List<TowerViolation> datas = towerViolationCount.getData();
                    bindData(datas);
                    violationCountTv.setText(towerViolationCount.getCount() + "次");
                    break;
            }
        }
    };

    private void bindData(List<TowerViolation> datas) {
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            towerViolationList = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            towerViolationList.addAll(datas);
        }
        showEmptyView(towerViolationList.size() == 0);
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        towerViolationAdapter.setDataList(towerViolationList);
    }

    private void showEmptyView(boolean isEmpty){
        if(isEmpty){
            emptyImg.setVisibility(View.VISIBLE);
        }else {
            emptyImg.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tower_violation_list);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        titleTv.setText(R.string.tower_violation);

        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);
        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        towerViolationList =  new ArrayList<>();
        towerViolationAdapter = new TowerViolationListAdapter(this, towerViolationList);
        towerViolationAdapter.setOnClickListener(this);
        dataRv.setAdapter(towerViolationAdapter);
        dataRv.setItemAnimator(new DefaultItemAnimator());
        dataRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        processDate(new Date(), new Date());
    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = towerViolationList.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getTowerViolationList("搜索中…");
            }
        }, 500);
    }

    public void getTowerViolationList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this,"constructionid"));
            jsonObject.put("pageNum", pageIndex + "");
//            jsonObject.put("equipmentId", 1 + "");//设备Id 获取某个塔吊设备的吊装循环数据、违章数据时必传，塔吊违章数据不需要传
            jsonObject.put("type", 1 + "");//0：正常；1：违章 只有获取违章数据、塔吊违章数据时传1，获取吊装循环数据不需要传
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/towerCraneWorkCycle/query/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    TowerViolationCountRes res = gson.fromJson(json, TowerViolationCountRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.UPDATE;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                        if (pageIndex == 1)
                        {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else
                        {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                    }
                }else{
                    showToast("系统异常");
                    if (pageIndex == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
                if (pageIndex == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    @OnClick({R.id.back_tv, R.id.search_date_tv})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back_tv:
                finish();
                break;
            case R.id.search_date_tv:
                Intent intent = new Intent(this, TimePickerActivity.class);
                startActivityForResult(intent, 0);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(requestCode == 0 && data != null){
                DayTimeEntity startDay = (DayTimeEntity) data.getSerializableExtra("startDay");
                DayTimeEntity stopDay = (DayTimeEntity) data.getSerializableExtra("stopDay");
                processDate(startDay, stopDay);
            }
        }
    }

    private void processDate(DayTimeEntity startDay, DayTimeEntity stopDay){
        startTime = dateFormat(startDay);
        endTime = dateFormat(stopDay);
        searchDateTv.setText(startTime  + " 至 " + endTime);
        initData();
    }

    private String dateFormat(DayTimeEntity dayTimeEntity){
        StringBuffer dateSb = new StringBuffer();
        dateSb.append(dayTimeEntity.getYear() + "-");
        if(dayTimeEntity.getMonth() > 9){
            dateSb.append(dayTimeEntity.getMonth() + "-");
        }else {
            dateSb.append( "0" + dayTimeEntity.getMonth() + "-");
        }
        if(dayTimeEntity.getDay() > 9){
            dateSb.append(dayTimeEntity.getDay());
        }else {
            dateSb.append( "0" + dayTimeEntity.getDay());
        }
        return dateSb.toString();
    }

    private void processDate(Date startdate, Date enddate){
        startTime = dateFormat(startdate);
        endTime = dateFormat(enddate);
        searchDateTv.setText(startTime  + " 至 " + endTime);
        initData();
    }

    private String dateFormat(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    @Override
    public void onClick(Object o) {
        TowerViolation towerViolation = (TowerViolation) o;
        if(towerViolation == null){
            return;
        }
        Intent intent = new Intent(this, TowerViolationDetailActivity.class);
        intent.putExtra("towerViolation", towerViolation);
        startActivity(intent);
    }
}
